package com.wenhai.leetcode.tree;

import java.util.TreeMap;

/**
 *https://leetcode-cn.com/problems/design-add-and-search-words-data-structure/
 *
 * @author wenhai
 * @date   2021/3/25
 */
public class _211添加与搜索单词数据结构设计 {
    private Node root;

    /** Initialize your data structure here. */
    public _211添加与搜索单词数据结构设计() {
        this.root = new Node();
    }

    public void addWord(String word) {
        Node cur = this.root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (cur.next.get(c) == null) {
                cur.next.put(c, new Node());
            }
            cur = cur.next.get(c);
        }
        if (!cur.isWord) {
            cur.isWord = true;
        }

    }

    public boolean search(String word) {
        return match(this.root, word, 0);
    }

    private boolean match(Node node, String word, int index) {
        if (index == word.length()) {
            return node.isWord;
        }
        char c = word.charAt(index);
        if (c != '.') {
            if (node.next.get(c) == null) {
                return false;
            }
            return match(node.next.get(c), word, index + 1);
        } else {
            for (char nextChar : node.next.keySet()) {
                if (match(node.next.get(nextChar), word, index + 1)) {
                    return true;
                }
            }
            return false;
        }
    }


    private class Node {
        boolean isWord;
        TreeMap<Character, Node> next;

        Node() {
            this(false);
        }

        Node(boolean isWord) {
            this(isWord, new TreeMap<>());
        }

        Node(boolean isWord, TreeMap<Character, Node> next) {
            this.isWord = isWord;
            this.next = next;
        }
    }

}
